package cn.itcast.mobilebrowser.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import cn.itcast.mobilebrowser.R;
import cn.itcast.mobilebrowser.adapter.BookMarkAdapter;
import cn.itcast.mobilebrowser.model.BookMark;
import cn.itcast.mobilebrowser.viewmodel.BookMarkViewModel;

public class BookMarksFragment extends Fragment {

    private final String TAG = "BookMarksFragment";

    private static final String ARG_SECTION_NUMBER = "section_number";

    private BookMarkViewModel bookMarkViewModel;
    private List<BookMark> bookMarkList;

    private BookMarkAdapter bookMarkAdapter;
    private ListView listView;

    public BookMarksFragment() {
        // Required empty public constructor
    }


    public static BookMarksFragment newInstance(int index) {
        BookMarksFragment fragment = new BookMarksFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, index);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int index = 1;
        if (getArguments() != null) {
            index = getArguments().getInt(ARG_SECTION_NUMBER);
        }
        Log.d(TAG, "当前Fragment：" + index);

        // 测试数据初始化，生成东西放在test_data中
        this.initData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_book_marks, container, false);

        listView = root.findViewById(R.id.bookmark);

        this.initView();

        return root;
    }

    private void initView() {
        // 初始化适配器
        bookMarkAdapter = new BookMarkAdapter(requireActivity(), R.layout.web_item, bookMarkList);

        // 将适配器上的数据传递给listView,在activity_book_marks.xml中
        listView.setAdapter(bookMarkAdapter);

        // 为ListView注册一个监听器，当用户点击了ListView中的任何一个子项时，就会回调onItemClick()方法
        // 在这个方法中可以通过position参数判断出用户点击的是那一个子项
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BookMark bookMark = bookMarkList.get(position);
                Log.d(TAG, bookMark.getUrl());
                Toast.makeText(requireActivity(),"进入" + bookMark.getTitle(),Toast.LENGTH_SHORT).show();

                // 点击后传回链接给网页，requireAc 获取父activity，为它intent设置返回值
                Intent intent = new Intent();
                intent.putExtra("url", bookMark.getUrl());
                requireActivity().setResult(Activity.RESULT_OK, intent);
                requireActivity().finish();
            }
        });

        // 设置长按事件
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                // 生成popup菜单
                PopupMenu popupMenu = new PopupMenu(getContext(), view);
                popupMenu.getMenuInflater().inflate(R.menu.pop_menu_delete, popupMenu.getMenu());
                // 设置菜单点击事件
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        // 拿到要删除的对象
                        BookMark bookMark = (BookMark) listView.getItemAtPosition(position);

                        // 弹出确认对话框
                        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                        builder.setMessage(R.string.delete_alert_message)
                                .setPositiveButton(R.string.confirm, (dialog, which) -> {
                                    bookMarkViewModel.delete(bookMark);
                                })
                                .setNegativeButton(R.string.cancel, (dialog, which) -> {
                                    // 取消删除
                                });
                        builder.create().show();
                        return false;
                    }
                });
                // 显示菜单
                popupMenu.setGravity(Gravity.END);
                popupMenu.show();
                // 返回true屏蔽点击事件
                return true;
            }
        });
    }

    /**
     * 初始化数据以装填至列表
     */
    private void initData() {
        bookMarkList = new ArrayList<>();
        // 初始化ViewModel
        bookMarkViewModel = new ViewModelProvider(requireActivity()).get(BookMarkViewModel.class);

        // 观察书签表的数据，一旦数据有改动就更新list的数据
        // 此处的改动是指数据库数据被更新：增删改
        bookMarkViewModel.getAllBookMarks().observe(requireActivity(), new Observer<List<BookMark>>() {
            @Override
            public void onChanged(List<BookMark> bookMarks) {
                bookMarkList.clear();
                bookMarkList.addAll(bookMarks);
                // 通知适配器数据修改
                bookMarkAdapter.notifyDataSetChanged();
            }
        });

        // 用于测试的初始数据，第一次安装才用，之后记得注释再跑一次避免重复添加
        // this.addTestData();
    }

    private void addTestData() {
        BookMark bookMark1 = new BookMark("百度", "https://www.baidu.com/");
        bookMarkViewModel.insert(bookMark1);
        BookMark bookMark2 = new BookMark("字节跳动", "https://bytedance.com/zh/");
        bookMarkViewModel.insert(bookMark2);
        BookMark bookMark3 = new BookMark("哔哩哔哩", "https://www.bilibili.com/");
        bookMarkViewModel.insert(bookMark3);
        BookMark bookMark4 = new BookMark("必应", "https://www.bing.com/");
        bookMarkViewModel.insert(bookMark4);
    }


}